<script setup lang="ts">
import { flattenAreaData, type Area } from '@/utils/area'
import { showToast, type ActionSheetAction } from 'vant'
import { computed, onMounted, ref } from 'vue'
import b64ToBlob from 'b64-to-blob'
import { request } from '@/api'

//生日/所在地类型--------------------------------------------------
interface IPickerParams {
  selectedValues: string[]
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}
//头像半模态------------------------------------------------------
const isShowCamera = ref(false)

//生日弹窗框-----------------------------------------------------
const isShowBirthday = ref(false)
const date = new Date()
//当前日期选中项
const currentDate = ref([
  date.getFullYear().toString(),
  (date.getMonth() + 1).toString(),
  date.getDate().toString(),
])

//选择城市----------------------------------------------------------
const isShowArea = ref(false)
//省市区数据源
const columns = ref<Area[]>([])
const str = mk.getAreaColumns()
columns.value = JSON.parse(str)
const areaData = flattenAreaData(JSON.parse(str))

//选择职业---------------------------------------------------------
const columnsPro = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
//控制所在地半膜态显示
const showProfessionPopup = ref(false)

//拍照上传方法----------------------------------------------
const onClickCamera = async (action: ActionSheetAction, index: number) => {
  isShowCamera.value = false
  if (index === 0) {
    const data = await mk.pickerCamera()
    await uploadImg(data)
  } else {
    const data = await mk.pickerPhoto()
    await uploadImg(data)
  }
}
//拍照/相册上传封装--------------------------------------------
const uploadImg = async (str: string) => {
  //转换为二进制blob
  const file = b64ToBlob(str, 'image/jpeg')

  //解析数据
  const fd = new FormData()
  fd.append('file', file, Date.now() + '.jpeg')

  const res = await request.post<getAvatar>('member/profile/avatar', fd)
  profile.value.avatar = res.data.result.avatar
  showToast('上传成功')
}

//点击生日完成时的方法-------------------------------------------
//先切割年月日
const birthday = computed(() => {
  return profile.value.birthday.split('-')
})
const onSelectBirth = ({ selectedValues }: IPickerParams) => {
  profile.value.birthday = selectedValues.join('-')
  isShowBirthday.value = false
}

//点击地区完成时的方法-------------------------------------------
const onSelectArea = (data: IPickerParams) => {
  const pName = areaData[data.selectedValues[0]]
  const cName = areaData[data.selectedValues[1]]
  const aName = areaData[data.selectedValues[2]]

  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  profile.value.fullLocation = `${pName} ${cName} ${aName}`
  isShowArea.value = false
}

//点击职业完成时的方法-------------------------------------------
const onChangeProfession = (data: { selectedValues: string[] }) => {
  profile.value.profession = data.selectedValues[0]
  showProfessionPopup.value = false
}

//查用户数据-------------------------------------
const profile = ref({} as HDMUser)
onMounted(() => {
  profile.value = mk.queryUser()
})

//保存资料方法----------------------------------
const onSubmit = async () => {
  // 调用接口
  const res = await request.put('/member/profile', profile.value)
  // 4. 更新数据到鸿蒙App
  // 5. 修复用户数据更新到首选项中
  mk.updateUser(res.data.result)
  showToast('保存成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
      </van-image>
      <div class="avatar-btn" @click="isShowCamera = true">
        <span>修改头像</span>
      </div>
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        v-model="profile.birthday"
        @click="isShowBirthday = true"
      ></van-field>
      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        v-model="profile.fullLocation"
        @click="isShowArea = true"
      ></van-field>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        v-model="profile.profession"
        @click="showProfessionPopup = true"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="onSubmit"> 保存资料 </van-button>
    </div>
  </div>

  <!-- 修改头像弹窗框 -->
  <VanActionSheet
    v-model:show="isShowCamera"
    cancel-text="取消"
    @select="onClickCamera"
    :actions="[{ name: '拍照' }, { name: '相册' }]"
  />

  <!-- 生日头像弹窗框 -->
  <VanPopup v-model:show="isShowBirthday" position="bottom">
    <VanDatePicker
      title="请选择生日"
      :min-date="new Date('1900-01-01')"
      :max-date="new Date()"
      :model-value="birthday"
      @cancel="isShowBirthday = false"
      @confirm="onSelectBirth"
    />
  </VanPopup>

  <!-- 城市所在区 -->
  <VanPopup v-model:show="isShowArea" position="bottom">
    <VanPicker
      :columns="columns"
      @cancel="isShowArea = false"
      @confirm="onSelectArea"
      title="请选择所在地"
      :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"
    ></VanPicker>
  </VanPopup>

  <!-- 职业选择 -->
  <van-popup v-model:show="showProfessionPopup" round position="bottom">
    <van-picker
      title="请选择职业"
      :columns="columnsPro"
      @confirm="onChangeProfession"
      @cancel="showProfessionPopup = false"
    />
  </van-popup>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px #ccc;
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
